// 读取目录并且重命名文件为 xxx.bat，xxx 为从某个索引开始
let fs = require('fs').promises;
let path = require('path');
async function renameFilesInDirectory(directoryPath, startIndex, mappingFilePath) {
  try {
    // 确保目录存在且可访问
    let stats = await fs.stat(directoryPath);
    if (!stats.isDirectory()) {
      throw new Error(`${directoryPath} is not a directory.`);
    }
    // 读取目录内容
    let files = await fs.readdir(directoryPath);
    // 过滤出仅文件（排除子目录）
    let filePaths = files.map(file => path.join(directoryPath, file));
    let fileStatsPromises = filePaths.map(filePath => fs.stat(filePath));
    let fileStats = await Promise.all(fileStatsPromises);
    let onlyFiles = filePaths.filter((filePath, index) => fileStats[index].isFile());
    // 初始化映射对象
    let currentIndex = startIndex;
    let fileNameMapping = {};
    // 重命名文件并构建映射
    for (let oldFilePath of onlyFiles) {
      let oldFileName = path.basename(oldFilePath);
      let newFileName = `${currentIndex}.bat`;
      let newFilePath = path.join(directoryPath, newFileName);
      // 检查新文件名是否已存在，以避免覆盖
      let exists = await fs.access(newFilePath).then(() => true, () => false);
      if (exists) {
        console.warn(`File ${newFilePath} already exists. Skipping.`);
        continue;
      }
      await fs.rename(oldFilePath, newFilePath);
      console.log(`Renamed: ${oldFilePath} -> ${newFilePath}`);
      // 添加到映射表
      fileNameMapping[currentIndex] = oldFileName;
      currentIndex++;
    }
    // 将映射保存为 JSON 文件
    await fs.writeFile(mappingFilePath, JSON.stringify(fileNameMapping, null, 2), 'utf8');
    console.log(`File name mapping saved to ${mappingFilePath}`);
    console.log('All files have been renamed successfully.');
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}
// 使用示例
let directoryPath = 'D:\\360安全浏览器下载\\test'; // 替换为您的目标目录路径
let startIndex = 712; // 从哪个索引开始
let mappingFilePath = './file-name-mapping.json'; // 映射文件保存路径
renameFilesInDirectory(directoryPath, startIndex, mappingFilePath);

